package org.edu.modules.oa.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.RedisUtil;
import org.edu.modules.oa.config.QueryConditionTool;
import org.edu.modules.oa.entity.VeOaCarBaoXianEntity;
import org.edu.modules.oa.entity.VeOaCarInfoEntity;
import org.edu.modules.oa.service.IVeOaCarBaoXianService;
import org.edu.modules.oa.util.OssDownloadUtil;
import org.edu.modules.oa.vo.QueryCondition;
import org.edu.modules.oa.vo.VeOaCarBaoXianExcelVo;
import org.edu.modules.oa.vo.VeOaCarInfoTableVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags="车辆保险业务")
@RestController
@RequestMapping("oa/vehicleInsurance")
@Slf4j
public class VeOaCarBaoXianController {
    @Resource
    private IVeOaCarBaoXianService baoXianservice;
    @Autowired
    private RedisUtil redisUtil; // redis服务类
    //初始化保险列表
    @PostMapping(value = "/loadInsureTable")
    public Result<?> loadInsureTable(Integer current, Integer pageSize, VeOaCarBaoXianEntity veOaCarBaoXianEntity){
        System.out.println(veOaCarBaoXianEntity);
        HashMap<String, Object> map = baoXianservice.loadTable(current,pageSize,veOaCarBaoXianEntity);
        return Result.OK(map);
    }

    //查看保险详情
    @PostMapping(value = "/selectInsureById")
    public Result<?> selectInsureById(Integer id){
        VeOaCarBaoXianEntity veOaCarBaoXianEntity = baoXianservice.selectInsureById(id);
        return Result.OK(veOaCarBaoXianEntity);
    }

    //删除保险记录
    @PostMapping(value = "/deleteInsureById")
    public Result<?> deleteInsureById(Integer id){
        System.out.println(id+"=======");
        int result = baoXianservice.deleteInsureById(id);
        System.out.println(result+"成功删除");
        if(result != 0){
            return Result.OK();
        }
        return Result.error("删除失败！！！");
    }

    //删除多条保险记录
    @PostMapping(value = "/deleteInsureAll")
    public Result<?> deleteInsureAll(String ids){
        String [] arr = ids.split(",");
        for(String id : arr){
            if(!id.equals("") && id != null){
                System.out.println(id);
                baoXianservice.deleteInsureById(Integer.parseInt(id));
            }
        }
        return Result.OK();
    }

    //保险表格导出功能
    @GetMapping(value = "exportInsure")
    public ModelAndView exportInsure(){
        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //获取需要导出的Excel数据
        List<VeOaCarBaoXianEntity> list = baoXianservice.selectAllInsure();

        //把需要导出的数据转移到Excel数据类中
        List<VeOaCarBaoXianExcelVo> excelVoList = new ArrayList<>();
        for(VeOaCarBaoXianEntity bx : list){
            VeOaCarBaoXianExcelVo excelVo = new VeOaCarBaoXianExcelVo();
            excelVo.setCarName(bx.getCarName());
            excelVo.setFeiYongName(bx.getFeiYongName());
            excelVo.setFeiYongType(bx.getFeiYongType());
            excelVo.setBaoXianPrice(bx.getBaoXianPrice());
            // 时间类型转换成字符串实体类的类型也要改成String不然导出的时间类型对不上
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            excelVo.setBaoXianStartTime(formatter.format(bx.getBaoXianStartTime()));
            excelVo.setBaoXianEndTime(formatter.format(bx.getBaoXianEndTime()));
            excelVo.setCreateName(bx.getCreateName());
            excelVo.setBackInfo(bx.getBackInfo());
            excelVoList.add(excelVo);
        }
        mv.addObject(NormalExcelConstants.FILE_NAME, "保险记录");
        mv.addObject(NormalExcelConstants.CLASS, VeOaCarBaoXianExcelVo.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("保险记录", "导出人:"+user.getRealname(), "导出信息");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, excelVoList);
        return mv;
    }
    //导出模板
    @GetMapping(value = "exportList")
    public ModelAndView exportList(){
        System.out.println("*********************************************");
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<VeOaCarBaoXianExcelVo> excelVoList = new ArrayList<>();
        mv.addObject(NormalExcelConstants.FILE_NAME, "保险记录");
        mv.addObject(NormalExcelConstants.CLASS, VeOaCarBaoXianExcelVo.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("保险记录", "导出人:"+user.getRealname(), "导出信息");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, excelVoList);
        return mv;
    }
    //表格导入功能
    @PostMapping(value = "importExcel")
    public Result<?> importExcel(HttpServletRequest req, HttpServletResponse resp){
        System.out.println("准备开始导入表格");
        //先把需要导入的文件上传
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        //获取上传的文件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                //上传的数据的集合
                List<VeOaCarBaoXianExcelVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaCarBaoXianExcelVo.class, params);
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                //加入数据库使用的集合
                List<VeOaCarBaoXianEntity> entityList =new ArrayList<>();
                Integer count = 0;
                //循环遍历把需要的字段拷贝到数据库插入的集合中
                for(VeOaCarBaoXianExcelVo v : list){
                    VeOaCarBaoXianEntity veOaCarBaoXianEntity = new VeOaCarBaoXianEntity();
                    //查看车辆ID
                    VeOaCarInfoEntity veOaCarEntity = baoXianservice.selectCarId(v.getCarName());
                    if(null != veOaCarEntity){
                        count++;
                        veOaCarBaoXianEntity.setCarId(veOaCarEntity.getId());
                        veOaCarBaoXianEntity.setCarName(v.getCarName());
                        veOaCarBaoXianEntity.setBaoXianPrice(v.getBaoXianPrice());
                        // 字符串转换成时间类型
                        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        veOaCarBaoXianEntity.setBaoXianStartTime(formatter.parse(v.getBaoXianStartTime()));
                        veOaCarBaoXianEntity.setBaoXianEndTime(formatter.parse(v.getBaoXianEndTime()));
                        veOaCarBaoXianEntity.setFeiYongName(v.getFeiYongName());
                        veOaCarBaoXianEntity.setFeiYongType(v.getFeiYongType());
                        veOaCarBaoXianEntity.setBackInfo(v.getBackInfo());
                        veOaCarBaoXianEntity.setCreateBy(user.getId());
                        veOaCarBaoXianEntity.setCreateName(user.getRealname());
                        veOaCarBaoXianEntity.setTerminalId(1L);
                        entityList.add(veOaCarBaoXianEntity);
                    }else {
                        return Result.error("无"+v.getCarName()+"车辆信息");
                    }
                }
                for (VeOaCarBaoXianEntity a: entityList){
                    System.out.println(a);
                }
                baoXianservice.saveBatch(entityList);
                return Result.ok("文件导入条数：" + count);
            } catch (Exception e) {
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //修改保险记录
    @PostMapping(value = "/setInsureById")
    public Result<?> setInsureById(VeOaCarBaoXianEntity v,String startTime,String endTime )throws Exception{
        // 前端传过来的时间字符串转换成日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date sTime = formatter.parse(startTime.trim());
        Date eTime = formatter.parse(endTime.trim());
        System.out.println(sTime+"================================="+eTime);
        v.setBaoXianStartTime(sTime);
        v.setBaoXianEndTime(eTime);
        //获取用户信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        v.setUpdateBy(user.getUsername());
        v.setUpdateName(user.getRealname());
        System.out.println(v);
        int res = baoXianservice.setInsureById(v);
        if(res == 0){
            return Result.error(500,"修改失败了！！");
        }
        return Result.OK("修改成功！！！");
    }
    //查看全部车辆名称和id
    @PostMapping("/selectCar")
    public Result<?> selectCar(){
        List<VeOaCarInfoEntity> list = baoXianservice.selectCar();
        return Result.OK(list);
    }
    //新增保险记录
    @PostMapping("/addInsure")
    public Result<?> addInsure(VeOaCarBaoXianEntity v,String startTime,String endTime){
        // 前端传过来的时间字符串转换成日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date sTime= null;
        Date eTime= null;
        try {
            sTime = formatter.parse(startTime.trim());
            eTime = formatter.parse(endTime.trim());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        v.setBaoXianStartTime(sTime);
        v.setBaoXianEndTime(eTime);
        String carName = baoXianservice.selectCarById(v.getCarId()).getCarName();
        v.setCarName(carName);
        //获取用户信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        v.setCreateName(user.getRealname());
        v.setCreateBy(user.getId());
        v.setIsDeleted(0);
        v.setTerminalId(1L);
        int res = baoXianservice.addInsure(v);
        if(res == 0){
            return Result.error(500,"添加失败了");
        }
        return Result.OK();
    }

    //高级查询保险记录
    @PostMapping("/queryInsure")
    public Result<?> queryInsure(@RequestBody String queryArray){
        //获取前台传过来的对象集合
        Map<String, List<QueryCondition>> maps = (Map<String, List<QueryCondition>>) JSON.parse(queryArray);
        List<QueryCondition> list =new ArrayList<QueryCondition>(JSONArray.parseArray(maps.get("queryArray").toString(),QueryCondition.class));
        //判断条件是用or拼接还是and拼接
        String conditionStr =  QueryConditionTool.getQueryConditionTool().advancedQuery(list);
//        String queryCondition="";
//        for (QueryCondition query:list){
//            if (query.getRule().equals("or")) {
//                queryCondition=" or ";
//                break;
//            }
//            if (query.getRule().equals("and")) {
//                queryCondition=" and ";
//                break;
//            }
//        }
////      条件的字符串
//        String conditionStr = "where 1=1";
//        for (QueryCondition query : list) {
//            if (query.getRule().equals("eq")) {
//                conditionStr += queryCondition + query.getField() + " = '" + query.getVal() + "' ";
//            }
//            if (query.getRule().equals("like")) {
//                conditionStr += queryCondition + query.getField() + " like '%" + query.getVal() + "%' ";
//            }
//            if (query.getRule().equals("right_like")) {
//                conditionStr += queryCondition + query.getField() + " like '" + query.getVal() + "%' ";
//            }
//            if (query.getRule().equals("left_like")) {
//
//                conditionStr += queryCondition + query.getField() + " like '%" + query.getVal() + "' ";
//            }
//            if (query.getRule().equals("in")) {
//
//                conditionStr += queryCondition + query.getField() + " in '(" + query.getVal() + ")' ";
//            }
//            if (query.getRule().equals("ne")) {
//
//                conditionStr += queryCondition + query.getField() + " != '" + query.getVal() + "' ";
//            }
//            if (query.getRule().equals("gt")) {
//
//                conditionStr += queryCondition + query.getField() + " &gt; '" + query.getVal() + "' ";
//            }
//            if (query.getRule().equals("ge")) {
//
//                conditionStr += queryCondition + query.getField() + " &gt;= '" + query.getVal() + "' ";
//            }
//            if (query.getRule().equals("lt")) {
//
//                conditionStr += queryCondition + query.getField() + " &lt; '" + query.getVal() + "' ";
//            }
//            if (query.getRule().equals("le")) {
//
//                conditionStr += queryCondition + query.getField() + " &lt;= '" + query.getVal() + "' ";
//            }
//        }
        conditionStr += "and is_deleted = '0'";
        HashMap<String,Object> map = baoXianservice.checkBaoXianEitity(conditionStr);
        return Result.OK(map);
    }
    //保险表格导出功能
    @GetMapping(value = "exportInsureById")
    public ModelAndView exportInsureById(){
        // 判断这辆车的导出
        VeOaCarInfoTableVo carInfo = (VeOaCarInfoTableVo) redisUtil.get("carInfo");
        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //获取需要导出的Excel数据
        List<VeOaCarBaoXianEntity> list = baoXianservice.selectInsureInportById(carInfo.getId().intValue());

        //把需要导出的数据转移到Excel数据类中
        List<VeOaCarBaoXianExcelVo> excelVoList = new ArrayList<>();
        for(VeOaCarBaoXianEntity bx : list){
            VeOaCarBaoXianExcelVo excelVo = new VeOaCarBaoXianExcelVo();
            excelVo.setCarName(bx.getCarName());
            excelVo.setFeiYongName(bx.getFeiYongName());
            excelVo.setFeiYongType(bx.getFeiYongType());
            excelVo.setBaoXianPrice(bx.getBaoXianPrice());
            // 时间类型转换成字符串实体类的类型也要改成String不然导出的时间类型对不上
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            excelVo.setBaoXianStartTime(formatter.format(bx.getBaoXianStartTime()));
            excelVo.setBaoXianEndTime(formatter.format(bx.getBaoXianEndTime()));
            excelVo.setCreateName(bx.getCreateName());
            excelVo.setBackInfo(bx.getBackInfo());
            excelVoList.add(excelVo);
        }
        mv.addObject(NormalExcelConstants.FILE_NAME, "保险记录");
        mv.addObject(NormalExcelConstants.CLASS, VeOaCarBaoXianExcelVo.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("保险记录", "导出人:"+user.getRealname(), "导出信息");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, excelVoList);
        return mv;
    }

    //表格导入功能
    @PostMapping(value = "importExcelById")
    public Result<?> importExcelById(HttpServletRequest req, HttpServletResponse resp){
        // 判断这辆车的导入
        VeOaCarInfoTableVo carInfo = (VeOaCarInfoTableVo) redisUtil.get("carInfo");
        //先把需要导入的文件上传
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        //获取上传的文件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Integer count = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                //上传的数据的集合
                List<VeOaCarBaoXianExcelVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaCarBaoXianExcelVo.class, params);
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                //加入数据库使用的集合
                List<VeOaCarBaoXianEntity> entityList =new ArrayList<>();
                //循环遍历把需要的字段拷贝到数据库插入的集合中
                for(VeOaCarBaoXianExcelVo v : list){
                    VeOaCarBaoXianEntity veOaCarBaoXianEntity = new VeOaCarBaoXianEntity();
                    //查看车辆ID
                    VeOaCarInfoEntity veOaCarEntity = baoXianservice.selectCarId(v.getCarName());
                    if(null != veOaCarEntity && veOaCarEntity.getId() == carInfo.getId()){
                        count++;
                        veOaCarBaoXianEntity.setCarId(veOaCarEntity.getId());
                        veOaCarBaoXianEntity.setCarName(veOaCarEntity.getCarName());
                        veOaCarBaoXianEntity.setBaoXianPrice(v.getBaoXianPrice());
                        // 字符串转换成时间类型
                        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        veOaCarBaoXianEntity.setBaoXianStartTime(formatter.parse(v.getBaoXianStartTime()));
                        veOaCarBaoXianEntity.setBaoXianEndTime(formatter.parse(v.getBaoXianEndTime()));
                        veOaCarBaoXianEntity.setFeiYongName(v.getFeiYongName());
                        veOaCarBaoXianEntity.setFeiYongType(v.getFeiYongType());
                        veOaCarBaoXianEntity.setBackInfo(v.getBackInfo());
                        veOaCarBaoXianEntity.setCreateBy(user.getId());
                        veOaCarBaoXianEntity.setCreateName(user.getRealname());
                        veOaCarBaoXianEntity.setTerminalId(1L);
                        entityList.add(veOaCarBaoXianEntity);
                    }

                }
                baoXianservice.saveBatch(entityList);
                return Result.ok("文件导入条数：" + count);
            } catch (Exception e) {
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error(500,"导入失败了");
    }

    //获取模板下载地址
    @AutoLog(value = "车辆保险业务-模板地址获取")
    @ApiOperation(value = "模板地址", notes = "车辆保险业务-模板地址获取")
    @PostMapping(value = "/getUrl")
    public Result<T> getUrl() throws Exception {
        Result result = new Result();
        String url= OssDownloadUtil.getOssDownloadUtil().downFileFromOSS("保险记录查询模板.xls");
        result.success(url);
        return result;
    }


}
